#!/usr/bin/env python
# -*- coding: utf-8 -*-
###################################################################
# Author: wang donghao
# Date  : 2020.11
# Email : dd.parkhere@gmail.com
###################################################################

from dayu_widgets.qt import *
import os
import sys
from dayu_widgets.line_edit import MLineEdit
from dayu_widgets.tool_button import MToolButton
from dayu_widgets.divider import MDivider
from dayu_widgets.label import MLabel


class LauncherListView(QListView):
    item_clicked_sig = Signal(str)

    def __init__(self, parent):
        super(LauncherListView, self).__init__(parent=parent)
        self._model = QStandardItemModel(self)
        self.setModel(self._model)

        self.setIconSize(QSize(45, 45))
        self.__last_click_time = None
        self.clicked.connect(self.click)

    def click(self, *args, **kwargs):
        # time_now = int(str(datetime.datetime.now()).replace(' ', '').replace(':', '').replace('-', '').replace('.', ''))
        # if not self.__last_click_time:
        #     self.__last_click_time = time_now
        self.item_clicked_sig.emit(self.current_item_label())
        #     return
        # if time_now - self.__last_click_time < 500000:
        #     return
        # self.__last_click_time = time_now

    def append_item(self, label, img, display=''):
        item = QStandardItem()
        item.setIcon(QIcon(img))
        display_text = label if not display else display
        item.setText(display_text)
        item.setEditable(False)
        item.label = label
        self._model.appendRow(item)

    def current_item_label(self):
        current_item = self._model.itemFromIndex(self.currentIndex())
        return str(current_item.label)


class AddCustomExe(QDialog):
    custom_soft_info_sig = Signal(list)

    def __init__(self, parent):
        super(AddCustomExe, self).__init__(parent=parent)
        self._init_ui()

    def _init_ui(self):
        main_lay = QVBoxLayout()
        self.setWindowTitle(u'添加自定义程序')
        self.setMinimumWidth(500)
        layout = QFormLayout()
        self.icon_le = MLineEdit().file()
        self.icon_le.setReadOnly(True)
        layout.addRow(u'图标路径:', self.icon_le)
        self.icon_le.setPlaceholderText(u'请点击右侧按钮选择缩略图')
        self.exe_le = MLineEdit().file()
        self.exe_le.setReadOnly(True)
        layout.addRow(u'程序路径:', self.exe_le)
        self.exe_le.setPlaceholderText(u'请点击右侧按钮选择程序启动的路径')
        self.param_le = MLineEdit()
        self.param_le.setPlaceholderText(u'可选')
        layout.addRow(u'额外参数:', self.param_le)
        self.ok_pb = MToolButton().svg('success_line.svg').text_beside_icon()
        self.ok_pb.setText(u'确定')
        down_lay = QHBoxLayout()
        down_lay.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Minimum))
        main_lay.addLayout(layout)
        down_lay.addWidget(self.ok_pb)
        main_lay.addLayout(down_lay)
        self.setLayout(main_lay)
        self.ok_pb.clicked.connect(self.get_info)

    def get_info(self):
        info = [self.icon_le.text(), self.exe_le.text(), self.param_le.text()]
        self.custom_soft_info_sig.emit(info)
        self.close()


class DeleteCustomSoftWin(QDialog):
    to_delete_items_sig = Signal(list)

    def __init__(self, parent):
        super(DeleteCustomSoftWin, self).__init__(parent=parent)
        self._init_ui()

    def _init_ui(self):
        self.setWindowTitle(u'删除自定义软件')
        lay = QVBoxLayout()
        lay.addWidget(MLabel(u'选中要删除的项目然后点击确定'))
        self.list_view = QListView()
        self.list_model = QStandardItemModel()
        self.list_view.setModel(self.list_model)
        lay.addWidget(self.list_view)
        self.ok_pb = MToolButton()
        self.ok_pb.setText(u'确定')
        lay.addWidget(self.ok_pb)
        self.setLayout(lay)
        self.ok_pb.clicked.connect(self.get_selected_item_labels)

    def append_row(self, label):
        item = QStandardItem()
        item.setText(label)
        self.list_model.appendRow(item)

    def add_rows(self, row_list):
        for row in row_list:
            self.append_row(row)

    def get_selected_item_labels(self):
        all_selected_indexes = self.list_view.selectedIndexes()
        all_labels = [self.list_model.itemFromIndex(each).text() for each in all_selected_indexes]
        self.to_delete_items_sig.emit(all_labels)
        self.close()


class LauncherWin(QDialog):
    BackgroundColor = QColor(255, 255, 255)
    BorderColor = QColor(255, 255, 255)

    def __init__(self, parent=None):
        super(LauncherWin, self).__init__(parent=parent)
        self._init_ui()

    def _init_ui(self):
        self.setWindowFlags(Qt.FramelessWindowHint|Qt.WindowStaysOnTopHint)
        self.setFixedWidth(400)
        main_layout = QVBoxLayout()
        # main_layout.setSpacing(0)
        main_layout.setContentsMargins(0, 0, 0, 0)
        self.top_widget = QLabel()
        self.top_widget.setScaledContents(True)
        self.top_widget_layout = QGridLayout()
        self.top_widget.setLayout(self.top_widget_layout)
        self.top_widget_layout.setContentsMargins(0, 0, 0, 0)
        self.top_widget_layout.setSpacing(0)
        self.top_widget_layout.addWidget(QLabel())
        self.top_widget.setFixedHeight(175)
        # self.top_widget.setFixedWidth(400)
        # self.top_widget.setStyleSheet("QWidget{background-image: url(launcher-bg.jpg);background-repeat: no-repeat }")
        self.top_widget.setPixmap(QPixmap(os.environ['WOKWOK_ROOT'] + '/resources/icons/launcher-bg.jpg'))
        # self.top_widget.setAutoFillBackground(True)
        # self.top_widget.setInputMethodHints(Qt.ImhNone)
        # self.top_widget.setAttribute(Qt.WA_TranslucentBackground, True)
        main_layout.addWidget(self.top_widget)

        divider_1 = MDivider(u'系统工具')
        divider_1.setStyleSheet("QWidget{background-color: rgba(0, 0, 0, 10);}")
        main_layout.addWidget(divider_1)

        self.system_tool_list_view = LauncherListView(self)
        self.system_tool_list_view.setMaximumWidth(self.width())
        self.system_tool_list_view.setViewMode(QListView.IconMode)

        self.system_tool_list_view.setStyleSheet("border:none;background:none;")
        main_layout.addWidget(self.system_tool_list_view)

        divider_2 = MDivider(u'DCC')
        divider_2.setStyleSheet("QWidget{background-color: rgba(0, 0, 0, 10);}")
        main_layout.addWidget(divider_2)

        self.dcc_list_view = LauncherListView(self)
        self.dcc_list_view.setMaximumWidth(self.width())
        self.dcc_list_view.setViewMode(QListView.IconMode)
        self.dcc_list_view.setStyleSheet("border:none;background:none;")
        main_layout.addWidget(self.dcc_list_view)

        divider_2 = MDivider(u'自定义')
        divider_2.setStyleSheet("QWidget{background-color: rgba(0, 0, 0, 10);}")
        main_layout.addWidget(divider_2)

        self.custom_pb = MToolButton().medium().svg('add_line.svg').text_beside_icon()
        self.custom_pb.setMinimumWidth(60)
        self.custom_pb.setText(u'新增')

        self.delete_pb = MToolButton().medium().svg('minus_line.svg').text_beside_icon()
        self.delete_pb.setMinimumWidth(60)
        self.delete_pb.setText(u'删除')

        self.exit_pb = MToolButton().medium().svg('close_fill.svg').text_beside_icon()
        self.exit_pb.setMinimumWidth(75)
        self.exit_pb.setText(u'退出程序')
        self.exit_pb.clicked.connect(sys.exit)

        custom_pb_lay = QHBoxLayout()
        custom_pb_lay.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Minimum))
        custom_pb_lay.addWidget(self.custom_pb)
        custom_pb_lay.addWidget(self.delete_pb)
        custom_pb_lay.addWidget(self.exit_pb)
        custom_lay = QVBoxLayout()
        custom_lay.setContentsMargins(0, 0, 10, 7)
        self.custom_list_view = LauncherListView(self)
        self.custom_list_view.setMaximumWidth(self.width())
        self.custom_list_view.setViewMode(QListView.IconMode)
        self.custom_list_view.setStyleSheet("border:none;background:none;")
        custom_lay.addWidget(self.custom_list_view)
        custom_lay.addLayout(custom_pb_lay)

        main_layout.addLayout(custom_lay)

        self.setLayout(main_layout)

        self._desktop = QApplication.instance().desktop()
        self.pos_offset = [0, 0]

        self.leave_timer = QTimer()
        self.leave_timer.timeout.connect(self.close)

    def show(self):
        super(LauncherWin, self).show()
        self.startPos = QPoint(
            self._desktop.screenGeometry().width() - self.width() + self.pos_offset[0] + self.width()/5 + 5,
            self._desktop.availableGeometry().height() - self.height() + self.pos_offset[1])
        self.endPos = QPoint(
            self._desktop.screenGeometry().width() - self.width() + self.pos_offset[0] + self.width()/5 + 5,
            self._desktop.availableGeometry().height() - self.height() + 50 + self.pos_offset[1])
        self.move(self.startPos)
        self.initAnimation(self.endPos, self.startPos)

    def initAnimation(self, startPos, endPos):
        # 往上移动动画
        moveAnimation = QPropertyAnimation(self, "pos")
        moveAnimation.setStartValue(startPos)
        moveAnimation.setEndValue(endPos)
        moveAnimation.setEasingCurve(QEasingCurve.OutSine)
        moveAnimation.setDuration(100)  # 在5秒的时间内完成
        animationGroup = QParallelAnimationGroup(self)
        animationGroup.addAnimation(moveAnimation)
        animationGroup.start()

    def leaveEvent(self, event):
        self.leave_timer.start(500)
        # self.close()

    def enterEvent(self, event):
        self.leave_timer.stop()

    def paintEvent(self, event):
        super(LauncherWin, self).paintEvent(event)
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)  # 抗锯齿

        rectPath = QPainterPath()  # 圆角矩形
        triPath = QPainterPath()  # 底部三角形

        height = self.height() - 8  # 往上偏移8
        rectPath.addRoundedRect(QRectF(0, 0, self.width(), height), 5, 5)
        x = self.width() / 5 * 4
        triPath.moveTo(x, height)  # 移动到底部横线4/5处
        # 画三角形
        triPath.lineTo(x + 6, height + 8)
        triPath.lineTo(x + 12, height)

        rectPath.addPath(triPath)  # 添加三角形到之前的矩形上

        # 边框画笔
        painter.setPen(QPen(self.BorderColor, 1, Qt.SolidLine,
                            Qt.RoundCap, Qt.RoundJoin))
        # 背景画刷
        painter.setBrush(self.BackgroundColor)
        # 绘制形状
        painter.drawPath(rectPath)
        # 三角形底边绘制一条线保证颜色与背景一样
        painter.setPen(QPen(self.BackgroundColor, 1,
                            Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
        painter.drawLine(x, height, x + 12, height)


if __name__ == '__main__':
    import sys
    from dayu_widgets.qt import QApplication

    app = QApplication(sys.argv)
    test = LauncherWin()
    from dayu_widgets.theme import MTheme
    light = MTheme('light')
    light.apply(test)
    test.show()
    sys.exit(app.exec_())




